<template>
  <div class="app-container layout-container column-layout">
    <!-- 过滤 start -->
    <div class="app-container search-box">
      <el-form ref="ruleFormRef" :model="tableParams" label-width="120px" class="demo-ruleForm">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="合同编号" prop="contractNo">
              <el-input v-model="tableParams.contractNo" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="tableParams.contractName" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同类型" prop="contractTypeId">
              <el-select placeholder="请选择" v-model="tableParams.contractTypeId">
                <el-option label="全部" value=" "></el-option>
                <el-option
                  v-for="item in typeListOptions"
                  :key="item.contractTypeId"
                  :label="item.contractTypeName"
                  :value="item.contractTypeId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="签约公司" prop="signId">
              <el-select placeholder="请选择" v-model="tableParams.signId">
                <el-option label="全部" value=" "></el-option>
                <el-option v-for="item in signOptions" :key="item.signId" :label="item.enterpriseName" :value="item.signId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同客户" prop="customerId">
              <el-select filterable placeholder="请选择" v-model="tableParams.customerId">
                <el-option label="全部" value=" "></el-option>
                <el-option
                  v-for="item in customerOptions"
                  :key="item.customerId"
                  :label="item.customerName + '-' + item.customerMobile + '-' + item.customerAddress"
                  :value="item.customerId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同状态" prop="status">
              <el-select placeholder="请选择" v-model="tableParams.status">
                <el-option label="全部" value=" "></el-option>
                <el-option label="待生成" :value="0"></el-option>
                <el-option label="审核中" :value="1"></el-option>
                <el-option label="签约中" :value="2"></el-option>
                <el-option label="执行中" :value="3"></el-option>
                <el-option label="已作废" :value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="text-align: right">
            <el-button type="primary" icon="Search" @click="submitForm">查询</el-button>
            <el-button type="primary" plain icon="RefreshRight" @click="resetForm(ruleFormRef)">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!--  过滤 end  -->
    <div class="sticky" style="margin-top: 16px">
      <el-row class="table-head">
        <el-col :span="4" style="text-align: center"> 合同名称</el-col>
        <el-col :span="4" style="text-align: center"> 合同类型&形式</el-col>
        <el-col :span="5" style="text-align: center"> 签约公司</el-col>
        <el-col :span="3" style="text-align: center"> 合同总金额</el-col>
        <el-col :span="3" style="text-align: center"> 合同状态</el-col>
        <el-col :span="3" style="text-align: center"> 合同预算报价单</el-col>
        <el-col :span="2" style="text-align: center"> 操作</el-col>
      </el-row>
    </div>
    <!-- 列表 -->
    <div class="table-list" v-loading="loading">
      <el-empty description="暂无数据" :image-size="60" v-if="!orderDataList.length && !loading" />
      <div class="goods" v-for="goods in orderDataList" :key="goods.contractId">
        <div class="business-name">
          <div class="left">
            <span class="contract-number" style="padding-left: 10px">合同编号：{{ goods.contractNo || "-" }}</span>
            <span class="contract-number" style="padding-left: 30px" v-if="goods.signingTime">签约时间：{{ goods.signingTime || "-" }}</span>
          </div>
          <div class="right">
            <p>
              <span class="contract-number"
                >合同客户：{{ goods.customerName || "-" }} / {{ goods.customerMobileCode || "-" }} /
                {{ goods.customerAddress || "-" }}</span
              >
            </p>
          </div>
        </div>
        <el-row>
          <el-col :span="4">{{ goods.title || "-" }}</el-col>
          <el-col :span="4"
            ><span v-if="goods.contractType">{{ goods.contractType }}-</span
            ><span>{{ signingList[goods.signingMethod] }}</span></el-col
          >
          <el-col :span="5">{{ goods.signCompany || "-" }}</el-col>
          <el-col :span="3">
            <span style="color: #ff3333">¥{{ goods.totalAmount || "-" }}</span>
          </el-col>
          <el-col :span="3">
            <el-tag v-show="goods.status == 0" type="warning">待生成</el-tag>
            <el-tag v-show="goods.status == 1" class="ml-2" color="#D9EDFF">审批中</el-tag>
            <el-tag v-show="goods.status == 2" class="ml-2" color="#D9EDFF">签约中</el-tag>
            <el-tag v-show="goods.status == 3" class="ml-2" color="#D9EDFF">执行中</el-tag>
            <el-tag v-show="goods.status == 4" class="ml-2" type="info">已作废</el-tag>
          </el-col>
          <el-col :span="3">{{ goods.budgetName || "-" }}</el-col>
          <el-col :span="2">
            <div class="table-operate">
              <el-button
                v-for="(button, index) in getVisibleButtons(goods)"
                :key="index"
                type="primary"
                link
                @click="button.action"
              >
                {{ button.text }}
              </el-button>
              <div v-if="showDropdownitem(goods)">
                <el-dropdown @command="e => handleCommand(e, goods)" v-if="goods.status != 4">
                  <span class="el-dropdown-link" style="font-size: 14px"
                    >展开
                    <el-icon class="el-icon--left">
                      <arrow-down />
                    </el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        v-for="(item, index) in filteredDropdownItems(goods)"
                        :key="index"
                        :command="item.command"
                        :style="item.style"
                      >
                        {{ item.text }}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <custom-pagination
      :total="listTotal"
      :background="false"
      v-model:limit="tableParams.size"
      v-model:page="tableParams.current"
      layout="total, sizes, prev, pager, next, jumper"
      @pagination="handelPage"
    >
    </custom-pagination>
    <!-- 作废弹窗   -->
    <div class="delete-dialog">
      <el-dialog :show-close="false" v-model="centerDialogVisible" :title="title + '-' + contractNo" width="400px" center>
        <span>你确定要作废此合同吗？作废后合同信息及合同文件均被删除。</span>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="centerDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleDelete">删除</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <!-- 查看合同   -->
    <file-preview ref="roleRef" />
    <!-- 上传签约合同 -->
    <el-dialog
      v-model="pdfDialogVisible"
      title="上传合同"
      width="470px"
      style="margin-top: 150px !important; border-radius: 10px"
      center
    >
      <pdf-upload
        v-if="pdfDialogVisible"
        :fileList="logoImageList"
        :accept="'.pdf,.jpg,.jpeg,.png'"
        multiple
        :max-size="20"
        :max-length="50"
        @upload-success="uploadLogoImageList"
        @upload-remove="uploadImageListRemove"
      />
      <template #footer>
        <div class="upload-but" style="text-align: center">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="postUpload" :disabled="logoImageList.length <= 0">确认上传</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 电子签约   -->
    <el-dialog
      v-model="electronicVisible"
      title="合同电子签约"
      width="485px"
      style="margin-top: 150px !important; border-radius: 10px"
      center
    >
      <el-form label-position="top" label-width="100px" :model="formLabelAlign" style="max-width: 460px">
        <el-form-item label="客户姓名">
          <el-input v-model="formLabelAlign.customerName" disabled />
        </el-form-item>
        <el-form-item label="客户身份证号">
          <el-input v-model="formLabelAlign.customerIdCard" disabled />
        </el-form-item>
        <el-form-item label="客户手机号">
          <el-input v-model="formLabelAlign.customerMobileCode" disabled />
        </el-form-item>
        <el-form-item label="客户地址">
          <el-input v-model="formLabelAlign.customerAddress" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="upload-but" style="text-align: center">
          <div v-if="signUrl == ''">
            <el-button @click="electronicVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="subLoading">发起签约</el-button>
          </div>
          <el-button v-else class="copy" type="primary" @click="handleCopyUrl">复制客户签约地址</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看签约合同   -->
    <el-dialog
      v-model="imgVisible"
      title="查看签约合同"
      width="455px"
      style="margin-top: 150px !important; border-radius: 10px"
      center
    >
      <div>
        <div class="upload-file-li" v-if="fileListData.length > 0">
          <div v-for="(item, index) in fileListData" :key="item" class="upload-file-item">
            <el-image style="width: 24px; height: 24px" :src="item.fileUrl" :fit="'fit'" :preview-src-list="[item.fileUrl]">
              <template #error>
                <div class="image-slot">
                  <img
                    @click="handlePdf(item.fileUrl)"
                    style="width: 24px; height: 24px; cursor: pointer"
                    src="@/assets/images/errpdf.png"
                    alt=""
                  />
                </div>
              </template>
            </el-image>
            <div class="flile-name">{{ item.name || item.fileName }}</div>
          </div>
        </div>
        <el-empty v-else description="暂无数据" image-size="50" />
      </div>
    </el-dialog>
    <!-- 发起整改增减项   -->
    <div class="delete-dialog">
      <el-dialog :show-close="false" v-model="visible" :title="rectificationTitle" width="400px" center>
        <div class="flex">
          <div style="margin-right: 40px"><span style="color: red">*</span>是否创建报价变更单</div>
          <el-radio-group v-model="radio" class="ml-4">
            <el-radio :label="1" size="large">是</el-radio>
            <el-radio :label="2" size="large">否</el-radio>
          </el-radio-group>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="handleGotoAdd">下一步</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from "element-plus";
import {
  contracList,
  contractSignList,
  customerList,
  typeList,
  deleteManage,
  uploadFile,
  imgDetail,
  initiate,
  contractFileDown,
  checkReform
} from "@/apis/template/index.js";
import { ref, reactive, computed } from "vue";
import { FormInstance } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { downloadPDF, handelCopy } from "@/utils/util";
import { microAppMainRouter } from "@/microApp/utils.js";

const router = useRouter();
const route = useRoute();
const ruleFormRef = ref<FormInstance>();
const contractId = ref(); // 合同ID
const contractNo = ref(); // 合同编号
const customerId = ref(); // 客户id
const budgetId = ref(); // 预算报价Id
const roleRef = ref();
const loading = ref(false);
const subLoading = ref(false);
const signOptions = ref([]);
const customerOptions = ref([]);
const typeListOptions = ref([]);
const logoImageList = ref([]);
const centerDialogVisible = ref(false);
const visible = ref(false); // 创建增减项单弹窗
const pdfDialogVisible = ref(false);
const electronicVisible = ref(false); // 电子签约
const imgVisible = ref(false); // 查看签约合同
const listTotal = ref(0);
const radio = ref(2); // 是否创建预算报价增减项单
const title = ref("");
const signUrl = ref(""); // 签约地址
const rectificationTitle = ref(""); // 签约地址
const orderDataList = ref([]);
const fileListData = ref([]); //签约合同
const tableParams = reactive({
  current: 1,
  size: 10,
  contractNo: route.query.contractNo || "",
  contractName: "",
  contractTypeId: " ",
  signId: " ",
  customerId: " ",
  status: " "
});
const formLabelAlign = ref({
  customerName: "",
  customerIdCard: "",
  customerMobileCode: "",
  customerAddress: ""
});
//定义按钮
const getVisibleButtons = goods => {
  const buttons = [
    {
      condition: () => !!goods.fileUrl,
      text: "查看",
      action: () => handelClickDetail(goods)
    },
    {
      condition: () => goods.isReform,
      text: "发起整改",
      action: () => handleCommand(1, goods)
    },
    {
      condition: () => goods.isChange,
      text: "发起增减项",
      action: () => handleCommand(2, goods)
    },
    {
      condition: () => goods.status === 0 || goods.status === 2,
      text: "生成合同文件",
      action: () => handleCommand(3, goods)
    },
    {
      condition: () => goods.signingMethod === 2 && goods.status === 2,
      text: "电子签约",
      action: () => handleCommand(4, goods)
    },
    {
      condition: () => (goods.status === 2 || goods.status === 3) && goods.signingMethod === 1,
      text: "上传签约合同",
      action: () => handleCommand(5, goods)
    },
    {
      condition: () => goods.status === 3,
      text: "查看签约合同",
      action: () => handleCommand(6, goods)
    },
    {
      condition: () => goods.status === 3,
      text: "下载签约合同",
      action: () => handleCommand(7, goods)
    },
    {
      condition: () => goods.status === 1 || goods.status === 2 || goods.status === 3,
      text: "下载生成合同",
      action: () => handleCommand(8, goods)
    },
    {
      condition: () => goods.status === 0 || goods.status === 2,
      text: "作废",
      action: () => handleCommand(9, goods)
    }
  ];
  // 过滤可见按钮
  const filteredButtons = buttons.filter(btn => btn.condition());
  return filteredButtons.length <= 2 ? filteredButtons : [filteredButtons[0]];
};

//定义dropdown-item数据
const dropdownItems = [
  { command: 0, text: "查看", condition: goods => !!goods.fileUrl },
  { command: 1, text: "发起整改", condition: goods => goods.isReform },
  { command: 2, text: "发起增减项", condition: goods => goods.isChange },
  {
    command: 3,
    text: "生成合同文件",
    condition: goods => goods.status === 0 || goods.status === 2
  },
  {
    command: 4,
    text: "电子签约",
    condition: goods => goods.signingMethod === 2 && goods.status === 2
  },
  {
    command: 5,
    text: "上传签约合同",
    condition: goods => (goods.status === 2 || goods.status === 3) && goods.signingMethod === 1
  },
  {
    command: 6,
    text: "查看签约合同",
    condition: goods => goods.status === 3
  },
  {
    command: 7,
    text: "下载签约合同",
    condition: goods => goods.status === 3
  },
  {
    command: 8,
    text: "下载生成合同",
    condition: goods => goods.status === 1 || goods.status === 2 || goods.status === 3
  },
  {
    command: 9,
    text: "作废",
    style: { color: "#ff3333" },
    condition: goods => goods.status === 0 || goods.status === 2
  }
];
//判断按钮显示个数是否大于2 大于2返回true
const showDropdownitem = goods => {
  const arryButtonCount = dropdownItems.reduce((count, item) => count + item.condition(goods), 0);
  return arryButtonCount > 2;
};
// 过滤掉第一个满足条件的下拉项
const filteredDropdownItems = goods => {
  const visibleItems = dropdownItems.filter(item => item.condition(goods));
  visibleItems.shift();
  return visibleItems;
};
const signingList = ref(["", "纸质", "电子", "电子或纸质"]);
const handelPage = () => {
  orderDataList.value = [];
  getPageList();
};
// 获取列表数据
const getPageList = async () => {
  loading.value = true;
  try {
    const { data } = await contracList(tableParams);
    orderDataList.value = data.records;
    listTotal.value = data.total;
    loading.value = false;
  } catch (e) {
    loading.value = false;
  }
};
// 签约公司
const getSignList = async () => {
  const { data } = await contractSignList(tableParams);
  signOptions.value = data.list || [];
};
// 合同客户
const getCustomerList = async () => {
  const { data } = await customerList(tableParams);
  customerOptions.value = data || [];
};
// 合同客户
const getTypeList = async () => {
  const { data } = await typeList(tableParams);
  typeListOptions.value = data || [];
};
// 获取成功上传的附件
const uploadLogoImageList = data => {
  logoImageList.value.push({
    ...data
  });
};
// 删除上传
const uploadImageListRemove = index => {
  logoImageList.value.splice(index, 1);
};
const postUpload = async () => {
  await uploadFile({
    contractId: contractId.value,
    urlList: logoImageList.value
  });
  logoImageList.value = [];
  pdfDialogVisible.value = false;
  await getPageList();
  ElMessage.success("上传成功");
};
/*查看操作*/
const handelClickDetail = async row => {
  roleRef.value.open(row.contractId);
};
//查看签约合同pdf
const handlePdf = url => {
  roleRef.value.openPdf(url);
};
/*上传pdf*/
const handleUpload = () => {
  logoImageList.value = [];
  pdfDialogVisible.value = true;
};
// 关闭上传
const handleClose = () => {
  logoImageList.value = [];
  pdfDialogVisible.value = false;
};
/*操作展开 */
const handleCommand = (command, row) => {
  contractId.value = row.contractId;
  contractNo.value = row.contractNo;
  customerId.value = row.customerId;
  budgetId.value = row.budgetId;
  title.value = row.title;
  signUrl.value = "";
  let name = row.title + "-" + row.contractNo + ".pdf";
  switch (command) {
    case 0:
      handelClickDetail(row);
      break;
    case 1:
      rectificationTitle.value = "创建整改售后单";
      visible.value = true;
      break;
    case 2:
      gotoQuitePrice()
      break;
    case 3:
      handleGoto(row);
      break;
    case 4:
      formLabelAlign.value = { ...row };
      electronicVisible.value = true;
      break;
    case 5:
      handleUpload();
      break;
    case 6:
      getFileDetail();
      imgVisible.value = true;
      break;
    case 7:
      getContractFileDown(row.contractId);
      break;
    case 8:
      row.fileUrl && downloadPDF(row.fileUrl, name);
      break;
    case 9:
      centerDialogVisible.value = true;
      break;
  }
};
// 获取签约文件
const getFileDetail = async () => {
  const { data } = await imgDetail(contractId.value);
  fileListData.value = data;
};

// 获取签约文件
const getContractFileDown = contractId => {
  contractFileDown(contractId).then(res => {
    if (res.data) {
      window.open(res.data);
    }
  });
};
// 发起电子签约
const handleSubmit = async () => {
  subLoading.value = true;
  try {
    const { data } = await initiate({ contractNo: contractNo.value });
    if (data.signUrl) {
      signUrl.value = data.signUrl;
      ElMessage.success("发起成功，请复制客户签约地址签约");
    } else {
      electronicVisible.value = false;
      await getPageList();
    }
    subLoading.value = false;
  } catch (e) {
    subLoading.value = false;
  }
};
// 复制签约地址
const handleCopyUrl = () => {
  handelCopy(signUrl.value);
};
// 查询列表
const submitForm = () => {
  orderDataList.value = [];
  getPageList();
};
// 重置列表
const resetForm = (formEl: FormInstance | undefined) => {
  formEl.resetFields();
  orderDataList.value = [];
  tableParams.current = 1;
  tableParams.contractNo = "";
  tableParams.size = 10;
  getPageList();
};
// 生成合同
const handleGoto = row => {
  router.push({
    path: "/contracts-provided",
    query: {
      contractId: row.contractId,
      title: row.title
    }
  });
};
// 作废合同
const handleDelete = async () => {
  await deleteManage({ contractId: contractId.value });
  await getPageList();
  centerDialogVisible.value = false;
};
// 创建增减项整改
const handleGotoAdd = async () => {
  //是否创建预算报价增减项单 1是 2否
  if (radio.value == 1) {
    await gotoQuitePrice()
  } else {
    visible.value = false
    microAppMainRouter("push", {
      path: "/crm/after-sales-order",
      query: {
        contractId: contractId.value,
        customerId: customerId.value,
        afterSalesType: rectificationTitle.value == "创建整改售后单" ? 1 : 3
      }
    });
  }
};
const gotoQuitePrice = async () => {
  const { data } = await checkReform(contractId.value);
  if (data !== true) {
    ElMessage.error("存在进行中的变更单，无法再次发起！");
    return true;
  }
  const afterSalesType = rectificationTitle.value == "创建整改售后单" ? 1 : 3;
  const baseRouter = window.microApp.router.getBaseAppRouter();
  const routeUrl = baseRouter.resolve({
    path: "/designer/quote-price/following/change",
    query: {
      budgetId: budgetId.value,
      contractId: contractId.value,
      customerId: customerId.value,
      afterSalesType
    }
  });
  visible.value = false
  window.open(routeUrl.href, "_blank");
};
getTypeList();
getSignList();
getCustomerList();
getPageList();
</script>

<style scoped lang="scss">
@import "./index.scss";
// 过滤
.search-box {
  background-color: #f6f8fa;
  margin-bottom: 20px;

  :deep(.el-input__wrapper),
  :deep(.el-select__wrapper) {
    box-shadow: none;
    border-radius: 0;
  }
}

.upload-but {
  .el-button {
    width: 134px;
    height: 36px;
  }

  .copy {
    width: 280px;
  }
}
</style>
